﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Jungle.Code.BLL;
using Jungle.Code.Utils;
using System.Collections.Generic;
using Jungle.Code.DAL;

using Jungle.Code.ProductManager;
using Jungle.Code.CategoryManager;
using System.Drawing;
using Jungle.Code.Core;
using Jungle.Users;

	public partial class Products_Admin :   BaseAdminModule
	{
        public override void FillBaseInfo()
        {
            sysName = "Products";
        }
        public override void Main()
        {
        }

        string cmd = "";
        int id = 0;
        
        protected override void OnInit(EventArgs e)
        {
            SessionKeeper sk = new SessionKeeper();
            sk.SessionId = Session.SessionID;
            sk.GetData();

            UserManager user = new UserManager();
            user.UserId = sk.UserId;
            user.GetById();

            if (Request["pId"] != null)
                id = Convert.ToInt32(Request["pId"]);

            switch (Request["cmd"])
            {
                case "view":
                    Global_Menu.ActiveViewIndex = 1;                    
                    break;
                case "viewHidden":
                    Global_Menu.ActiveViewIndex = 1;
                    break;
                case "edit":
                    Global_Menu.ActiveViewIndex = 2;
                    if (id > 0) { PrepareViewForEdit(id); }
                    btn_ProductSaveChanges.Visible = true;
                    break;
                case "add":
                    Global_Menu.ActiveViewIndex = 2;
                    FillProductDdl(-1,-1);
                    btn_AddNewProduct.Visible = true;
                    break;
                case "addType":
                    Global_Menu.ActiveViewIndex = 3;
                    btn_TypeAdd.Visible = true;
                    break;
                default:
                    Global_Menu.ActiveViewIndex = 0;
                    break;
            }

            base.OnInit(e);
        }

        // --------------------------------------------------------------------------------------------
        public void PrepareViewForEdit(int productId)
        {
            Product p = new Product();

            p.ProductId = productId;
            p.GetByProductId();

            txt_ProductCatNum.Text = p.CatalogNumber.Trim();
            txt_ProductDesc.Text = p.Description.Trim();
            txt_ProductMarketPrice.Text = p.MarketPrice.ToString().Trim();
            txt_ProductMinOrder.Text = p.MinimalOrder.ToString().Trim();
            txt_ProductSitePrice.Text = p.Price.ToString().Trim();
            txt_ProductTitle.Text = p.Title.Trim();
            txt_ProductWeight.Text = p.Weight.ToString().Trim();
            if (p.Visible) { ddl_ProductVisible.SelectedIndex = 0; } else { ddl_ProductVisible.SelectedIndex = 1; }
            FillProductDdl(p.CategoryId, p.TypeId); //заполнение выпадающих списков значениями из БД

        }
        // --------------------------------------------------------------------------------------------
        public void FillProductDdl(int CategoryId, int TypeId)
        {
            JungleTreeMenu cat = new JungleTreeMenu();
            ProductType pt = new ProductType();

            cat.GetAll();
            ddl_ProductCatId.Items.Clear();
            foreach (JungleTreeMenu c in cat.MenuItemsList)
            {
                ListItem li = new ListItem(c.MenuText, c.ID.ToString());
                ddl_ProductCatId.Items.Add(li);
            }
            if (CategoryId >= 0)
            {
                ddl_ProductCatId.SelectedValue = CategoryId.ToString().Trim();
            }

            pt.GetAll();
            ddl_ProductTypes.Items.Clear();
            foreach (ProductType ppt in pt.ProductTypeList)
            {
                ListItem li = new ListItem(ppt.TypeDescription, ppt.TypeId.ToString());
                ddl_ProductTypes.Items.Add(li);
            }
            if (TypeId >= 0)
            {
                ddl_ProductTypes.SelectedValue = TypeId.ToString().Trim();
            }
        }
        // --------------------------------------------------------------------------------------------
        public void ProductSaveChanges(object sender, EventArgs e)
        {

            Product t = new Product();
            string err = "";

            t.ProductId = Convert.ToInt32(id);
            t.GetByProductId();

            if (txt_ProductCatNum.Text != "") { t.CatalogNumber = txt_ProductCatNum.Text; } else { t.CatalogNumber = "(не указан)"; }
            if (Convert.ToInt32(ddl_ProductCatId.SelectedValue) > 0) { t.CategoryId = Convert.ToInt32(ddl_ProductCatId.SelectedValue); } else { err = "(Ошибка при выборе категории)"; }
            if (txt_ProductDesc.Text != "") { t.Description = txt_ProductDesc.Text; } else { t.Description = "(не указано)"; }
            if (txt_ProductMarketPrice.Text != "") { t.MarketPrice = Convert.ToDouble(txt_ProductMarketPrice.Text); } else { t.MarketPrice = 0; }
            if (txt_ProductMinOrder.Text != "") { t.MinimalOrder = Convert.ToInt32(txt_ProductMinOrder.Text); } else { err = "(Укажите величину минимального заказа)"; }
            if (txt_ProductSitePrice.Text != "") { t.Price = Convert.ToDouble(txt_ProductSitePrice.Text); } else { err = "(Поле: \"Цена сайта\" обязательно для заполнения)"; }
            if (txt_ProductTitle.Text != "") { t.Title = txt_ProductTitle.Text; } else { err = "Поле \"Название продукта\" обязательно для заполнения"; }
            if (ddl_ProductTypes.SelectedValue != "") { t.TypeId = Convert.ToInt32(ddl_ProductTypes.SelectedValue); } else { err = "Укажите тип товара"; }
            if (ddl_ProductVisible.SelectedIndex == 0) { t.Visible = true; } else { t.Visible = false; }
            if (fu_Photo.HasFile)
            {
                deleteImage();
                t.ImagePath = SaveImage(fu_Photo);
            }

            if (txt_ProductWeight.Text != "") { t.Weight = Convert.ToDouble(txt_ProductWeight.Text); } else { t.Weight = 0; }
            if (err != "")
            {
                lbl_ResultAddProduct.Text = err;
                err = "";
            }
            else
            {
                t.Update();
                Response.Redirect("Modules.aspx?mod=Products&cmd=view");
            }

        }
        // --------------------------------------------------------------------------------------------
        public void ProductAdd(object sender, EventArgs e)
        {
            Product t = new Product();
            string err = "";

            if (txt_ProductCatNum.Text != "") { t.CatalogNumber = txt_ProductCatNum.Text; } else { t.CatalogNumber = "(не указан)"; }
            if (Convert.ToInt32(ddl_ProductCatId.SelectedValue) > 0) { t.CategoryId = Convert.ToInt32(ddl_ProductCatId.SelectedValue); } else { err = "<strong>(Ошибка при выборе категории)</strong>"; }
            if (txt_ProductDesc.Text != "") { t.Description = txt_ProductDesc.Text; } else { t.Description = "(не указано)"; }
            if (txt_ProductMarketPrice.Text != "") { t.MarketPrice = Convert.ToDouble(txt_ProductMarketPrice.Text); } else { t.MarketPrice = 0; }
            if (txt_ProductMinOrder.Text != "") { t.MinimalOrder = Convert.ToInt32(txt_ProductMinOrder.Text); } else { err = "<strong>(Укажите величину минимального заказа)</strong>"; }
            if (txt_ProductSitePrice.Text != "") { t.Price = Convert.ToDouble(txt_ProductSitePrice.Text); } else { err = "<strong>(Поле: \"Цена сайта\" обязательно для заполнения)</strong>"; }
            if (txt_ProductTitle.Text != "") { t.Title = txt_ProductTitle.Text; } else { err = "<strong>Поле \"Название продукта\" обязательно для заполнения</strong>"; }
            if (ddl_ProductTypes.SelectedValue != "") { t.TypeId = Convert.ToInt32(ddl_ProductTypes.SelectedValue); } else { err = "<strong>Укажите тип товара</strong>"; }
            if (ddl_ProductVisible.SelectedIndex == 0) { t.Visible = true; } else { t.Visible = false; }
            if (fu_Photo.HasFile)
            {
                t.ImagePath = SaveImage(fu_Photo);
            }
            else
            {
                t.ImagePath = "no_photo";
            }
            if (txt_ProductWeight.Text != "") { t.Weight = Convert.ToDouble(txt_ProductWeight.Text); } else { t.Weight = 0; }
            t.AddDate = DateTime.Now;

            if (err != "")
            {
                lbl_ResultAddProduct.Text = err;
                err = "";
            }
            else
            {
                t.Add();
                lbl_ResultAddProduct.Text = "Товар успешно добавлен";
            }
        }
        // --------------------------------------------------------------------------------------------
        public string SaveImage(FileUpload file)
        {
            

            string mask = "qwertyuiopasdfghjklzxcvbnm";
            Random rnd = new Random();
            string rndstr = "";
            for (int i = 0; i < 6; i++)
            {
                rndstr += mask[rnd.Next(0, 24)];
            }
            string fnamePreview = "";
            string fnameLarge = "";
            try
            {
                System.Drawing.Image loadedImg = System.Drawing.Image.FromStream(file.PostedFile.InputStream);

                #region Preview

                fnamePreview = "/UserFiles/Images/Content/imgPreview/" + rndstr + file.FileName;
                
                int h = 170;
                int width = 100;

                double d1 = Math.Round((double)loadedImg.Width / width, 4);
                double d2 = Math.Round((double)loadedImg.Height / d1, 4);
                int height = Convert.ToInt32(d2);

                Bitmap imgOutput = new Bitmap(width, height);
                imgOutput.MakeTransparent();
                imgOutput.MakeTransparent(Color.Black);

                Graphics newGraphics = Graphics.FromImage(imgOutput);
                newGraphics.Clear(Color.FromArgb(0, 255, 255, 255));

                newGraphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                newGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                newGraphics.DrawImage(loadedImg, 0, 0, width, height);
                newGraphics.Flush();

                if (file.FileName.ToLower().EndsWith(".jpg") || file.FileName.ToLower().EndsWith(".jpeg"))
                    imgOutput.Save(Server.MapPath(fnamePreview), System.Drawing.Imaging.ImageFormat.Jpeg);
                if (file.FileName.ToLower().EndsWith(".png"))
                    imgOutput.Save(Server.MapPath(fnamePreview), System.Drawing.Imaging.ImageFormat.Png);
                if (file.FileName.ToLower().EndsWith(".gif"))
                    imgOutput.Save(Server.MapPath(fnamePreview), System.Drawing.Imaging.ImageFormat.Gif);
                if (file.FileName.ToLower().EndsWith(".tiff"))
                    imgOutput.Save(Server.MapPath(fnamePreview), System.Drawing.Imaging.ImageFormat.Tiff);

                #endregion

                #region Large

                fnameLarge = "/UserFiles/Images/Content/imgLarge/" + rndstr + file.FileName;

                if (Convert.ToInt32(Math.Round((double)loadedImg.Width, 4)) > 455)
                {
                    width = 455;
                }
                else
                {
                    width = Convert.ToInt32(Math.Round((double)loadedImg.Width, 4));
                }


                d1 = Math.Round((double)loadedImg.Width / width, 4);
                d2 = Math.Round((double)loadedImg.Height / d1, 4);
                height = Convert.ToInt32(d2);

                
                Bitmap imgOutput2 = new Bitmap(width, height);
                imgOutput2.MakeTransparent();
                imgOutput2.MakeTransparent(Color.Black);

                newGraphics = Graphics.FromImage(imgOutput2);
                newGraphics.Clear(Color.FromArgb(0, 255, 255, 255));

                newGraphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                newGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                newGraphics.DrawImage(loadedImg, 0, 0, width, height);
                newGraphics.Flush();

                if (file.FileName.ToLower().EndsWith(".jpg") || file.FileName.ToLower().EndsWith(".jpeg"))
                    imgOutput2.Save(Server.MapPath(fnameLarge), System.Drawing.Imaging.ImageFormat.Jpeg);
                if (file.FileName.ToLower().EndsWith(".png"))
                    imgOutput2.Save(Server.MapPath(fnameLarge), System.Drawing.Imaging.ImageFormat.Png);
                if (file.FileName.ToLower().EndsWith(".gif"))
                    imgOutput2.Save(Server.MapPath(fnameLarge), System.Drawing.Imaging.ImageFormat.Gif);
                if (file.FileName.ToLower().EndsWith(".tiff"))
                    imgOutput2.Save(Server.MapPath(fnameLarge), System.Drawing.Imaging.ImageFormat.Tiff);


                #endregion
            }
            catch { fnamePreview = "ERROR"; }

            

            return fnamePreview + "," + fnameLarge;
        }
        // --------------------------------------------------------------------------------------------
        public bool deleteImage()
        {
            Product p = new Product();
            p.ProductId = id;
            p.GetByProductId();

            if (p.ImagePath.ToString().Trim() != "no_photo")
            {
                string[] ImagesUrls = p.ImagePath.ToString().Split(',');

                try 
                {
                    System.IO.FileInfo fiSmall = new FileInfo(ImagesUrls[0]);
                    if (fiSmall.Exists)
                    {
                        fiSmall.Delete();
                    }
                    System.IO.FileInfo fiLarge = new FileInfo(ImagesUrls[1]);
                    if (fiLarge.Exists)
                    {
                        fiLarge.Delete();
                    }
                    return true;
                }
                catch
                {
                    return false;
                }                          
                
            }
            return false;
        }
        // --------------------------------------------------------------------------------------------
        public void ProductTypeAdd(object sender, EventArgs e)
        {
            ProductType pt = new ProductType();
            if (txt_TypeTitle.Text != "") { pt.TypeDescription = txt_TypeTitle.Text; pt.Add(); Response.Redirect("/admin/Modules.aspx?mod=Products&cmd=default"); } else { lbl_ResultAddType.Text = "Тип не может быть с пустым названием."; }
        }

	}
